import * as roleService from '../../services/role';

export default {
  namespace: 'role',
  state: {
    roleList: [],
    permissions:[],//所有的权限
    rolepermissions: [],//角色选择的权限
    currentItem: {},
    modalType: 'create',
    permissionModalVisible:false,
    newKey:'',
  },
  reducers: {
    qryRolesSuc(state, { payload: roleList }) {
      return { ...state, roleList };
    },
    qryPermissionsSuc(state, { payload: permissions }) {
      return { ...state, permissions };
    },

    changePermissions(state, { payload }) {
      return { ...state, ...payload,};
    },

    showPermission(state, { payload }) {
      return { ...state, ...payload,newKey : new Date().getTime() + '' , permissionModalVisible: true};
    },
    hidePermission(state, { payload }) {
      return { ...state, ...payload,newKey : new Date().getTime() + '' , permissionModalVisible: false};
    }
  },
  effects: {    
    *queryList({ payload },{ call, put }) {
      const { body } = yield call(roleService.qryRoles,payload);
      yield put({ type: 'qryRolesSuc', payload: body.data });
    },
    *create({ payload },{ call, put }){
      const { body } = yield call(roleService.create,payload);
      yield put({ type: 'reload' });
    },
    *edit({ payload },{ call, put }){
      const { body } = yield call(roleService.update,payload);
      yield put({ type: 'reload' });
    },
    *remove({ payload },{ call, put }){
      const { body } = yield call(roleService.del,payload.id);
      yield put({ type: 'queryList', payload:payload.search });
    },     
    *getPermission({ payload },{ call, put }) {
      const { body } = yield call(roleService.qryPermissionList,payload);
      yield put({ type: 'qryPermissionsSuc', payload: body.data });
    },

    *permission({ payload },{ call, put }){
      const { body } = yield call(roleService.getRolePermission,payload.id);   
        yield put({
          type: 'showPermission',
          payload: {
            currentItem:payload,
            rolepermissions: body.data,
            modalType: 'setPermission',
          },
        });     
    },

    *setPermission({ payload },{ call, put }){
      const { body } = yield call(roleService.setRolePermission,payload);   
      yield put({type: 'reload' });    
      yield put({type: 'hidePermission' });     
    },
    *reload(action, { put }) {
      yield put({ type: 'queryList', payload:{ 'name':'' }});
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/sys/role') {
          dispatch({ type: 'getPermission',});
          dispatch({ type: 'queryList', payload:{ 'name':'' }});
        }
      });
    },
  },
};
